package hkr.vfu.bluecenter.backend;

import hkr.vfu.bluecenter.swipe_fragments.UpdateUIListener;

/**
 * Created by mattiasbowallius on 14/01/14.
 */
public class BluetoothRunnable implements Runnable {

    private static final String DATA_COMMAND = "[data";
    private static final String STOP_COMMAND = "[stop";
    private static final String D_COMMAND = "[d";
    private static final String E_COMMAND = "[e";
    private static final String S_COMMAND = "[s\r";
    private BluetoothSingleton bluetoothSingleton;
    private BluetoothTask bluetoothTask;

    public BluetoothRunnable(TaskRunnableBluetoothMethods bluetoothTask) {
        bluetoothSingleton = BluetoothSingleton.getInstance();
        this.bluetoothTask = (BluetoothTask) bluetoothTask;
    }

    @Override
    public void run() {
        try {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
            bluetoothTask.setBluetoothThread(Thread.currentThread());
            String command = bluetoothTask.getCommand();
            String macAddress = bluetoothTask.getMacAddress();
            bluetoothSingleton.executeCommand(macAddress, command);
            if (!command.equals(S_COMMAND)) {
                if (command.contains(DATA_COMMAND) || command.contains(D_COMMAND) || command.contains(E_COMMAND)) {
                    DataSingleton.getInstance()
                            .setLatestValues(readAndParseData(macAddress), macAddress);
                    bluetoothTask.getBluetoothManager().handler.obtainMessage(BluetoothManager.COMMAND_FINISHED, bluetoothTask)
                            .sendToTarget();
                } else if (command.contains(STOP_COMMAND)) {
                    readNewLineAnswer(macAddress);
                } else {
                    readOKAnswer(macAddress);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    private int[] readAndParseData(String macAddress) {
        String answer = bluetoothSingleton.readAnswerWithEnding(macAddress, BluetoothSingleton.END);
        String[] answerParts = answer.split("\r");
        for (int i = 0; i < answerParts.length; i++) {
            String part = answerParts[i].trim();
            part = "" + part;
            if (part.equals("DATA:")) {
                String[] values = answerParts[i + 1].split(" ");
                if (values.length > 1) {
                    int[] intValues = new int[values.length - 1];
                    for (int j = 0; j < values.length; j++) {
                        String value = values[j];
                        if (!value.equals("END")) {
                            int intValue = Integer.parseInt(value);
                            intValues[j] = intValue;
                        }
                    }
                    return intValues;
                }
            }
        }
        return null;
    }

    private boolean readNewLineAnswer(String macAddress) {
        String answer = bluetoothSingleton.readAnswerWithEnding(macAddress, BluetoothSingleton.STOP);
        return answer.equals("\r");
    }

    private boolean readOKAnswer(String macAddress) {
        String answer = bluetoothSingleton.readAnswerWithEnding(macAddress, BluetoothSingleton.OK);
        return answer.equals("OK");
    }

    interface TaskRunnableBluetoothMethods {

        /**
         * Sets the Thread that this instance is running on
         *
         * @param currentThread the current Thread
         */
        void setBluetoothThread(Thread currentThread);

        String getCommand();

        public UpdateUIListener getUpdateUIListener();

        public BluetoothManager getBluetoothManager();
    }
}
